import { Component } from "react";
import axios from "axios";
import fs from "fs";

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            imgdata: null,
        };

        // axios.defaults.baseURL = "https://www.httpbin.org";
        // axios.defaults.headers.common["Authorization"] = "AUTH_TOKEN123";
        // axios.defaults.headers.post["Content-Type"] =
        //     "application/x-www-form-urlencoded";
    }

    axiosGet = () => {
        // 上面的请求也可以这样做
        axios
            .get("https://www.httpbin.org/get", {
                params: {
                    ID: 12345,
                },
            })
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    };

    axiosPost = () => {
        axios
            .post(
                "https://www.httpbin.org/post",

                // 数据值为对象时 默认使用json格式
                {
                    firstName: "Fred",
                    lastName: "Flintstone",
                },

                // 补充一些配置
                {
                    // 补充配置如果与全局设置冲突会覆盖全局配置
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded",
                    },
                }
            )
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    };

    /* 批量发送请求 */
    axiosAll = () => {
        function getUserAccount() {
            return axios.get("https://www.httpbin.org/get?username=admin");
        }

        function getUserPermissions() {
            return axios.get("https://www.httpbin123.org/get?password=123456");
        }

        axios
            .all([getUserAccount(), getUserPermissions()])
            .then(
                // 所有请求都已成功
                axios.spread(function (res1, res2) {
                    // 两个请求现在都执行完成
                    console.log("acct", res1);
                    console.log("perms", res2);
                })
            )

            // 只要有一个失败 就进来catch
            .catch((err) => {
                console.log("err", err);
            });
    };

    axiosConfig = async () => {
        try {
            // 发送 POST 请求
            const result = await axios({
                method: "post",
                url: "https://www.httpbin123.org/post",
                data: {
                    firstName: "Fred",
                    lastName: "Flintstone",
                },
            });

            console.log("result", result);
        } catch (err) {
            console.error("err", err);
        }
    };

    /* 需要在纯node环境下操作 */
    axiosDownload = () => {
        // 获取远端图片
        axios({
            method: "get",
            url: "http://localhost:3000/logo192.png",
            responseType: "stream",
        })
            .then((response) => {
                console.log("下载成功！", response);
                response.data.pipe(
                    require("fs").createWriteStream("./fuckoff.jpg")
                );
                // this.setState({
                //     imgdata: response.data,
                // });
            })
            .catch((err) => {
                console.error("err", err);
            });
    };

    axiosInstance = () => {
        const instance = axios.create({
            baseURL: "https://www.httpbin.org",
            timeout: 3000,
            headers: { "X-Custom-Header": "foobar" },
        });

        instance
            .get("/get?username=admin")
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    };

    axiosInterceptor = () => {
        const instance = axios.create();

        // 添加请求拦截器
        instance.interceptors.request.use(
            function (config) {
                // 在发送请求之前做些什么
                config.headers["Authorization"] = "Bearer this is my token";
                return config;
            },
            function (error) {
                // 对请求错误做些什么
                return Promise.reject(error);
            }
        );

        // 添加响应拦截器
        instance.interceptors.response.use(
            function (response) {
                // 对响应数据做点什么
                return response.data;
            },
            function (error) {
                // 对响应错误做点什么
                return Promise.reject(error);
            }
        );

        instance
            .get("https://www.httpbin.org/get")
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    };

    axiosPostForm = () => {
        // 构造表单数据（方式1）
        const params = new URLSearchParams();
        params.append("param1", "value1");
        params.append("param2", "value2");

        // 方式2
        // import qs from 'qs';
        // const params = qs.stringify({ 'bar': 123 })

        axios
            .post("/post", params)
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    };

    render() {
        return (
            <>
                <img src={this.state.imgdata} />
                <button onClick={this.axiosGet}>发送GET请求</button>
                <br />
                <button onClick={this.axiosPost}>发送POST请求</button>
                <br />
                <button onClick={this.axiosAll}>批量请求</button>
                <br />
                <button onClick={this.axiosConfig}>配置请求</button>
                <br />
                <button onClick={this.axiosDownload}>下载图片</button>
                <br />
                <button onClick={this.axiosInstance}>使用instance</button>
                <br />
                <button onClick={this.axiosInterceptor}>使用拦截器</button>
                <br />
                <button onClick={this.axiosPostForm}>POST表单数据</button>
                <br />
            </>
        );
    }
}

export default App;
